

from rest_framework import serializers

from drfstudy.models import Student,Classes

# 学生序列化器
class StudentSerializer(serializers.ModelSerializer):
    # id = serializers.IntegerField(read_only=True,label='ID')
    # name = serializers.CharField(max_length=20,label='姓名')
    # age = serializers.IntegerField(required=False,label="年龄")
    # sex = serializers.IntegerField(required=False,label="性别")
    #
    # create_time = serializers.DateTimeField(required=False,label="创建时间")
    # update_time = serializers.DateTimeField(required=False,label="修改时间")
    #
    # # is_delete = serializers.BooleanField(default=False,label="逻辑删除",required=False)
    #
    #
    # def create(self, validated_data):
    #     return Student.objects.create(**validated_data)
    #
    # def update(self, instance, validated_data):
    #     instance.name = validated_data.get('name', instance.name)
    #     instance.age = validated_data.get('age', instance.age)
    #     instance.sex = validated_data.get("sex",instance.sex)
    #
    #     instance.save()
    #     return instance


    class_name = serializers.CharField(source="classes.name", read_only=True)
    class Meta:
        model = Student
        exclude = ["is_delete"]
        extra_kwargs = {
            # "age":{"min_value":1,"max_value":100}  # 针对年龄最小1 最大100
            # "class_sex": {"write_only": True},
            "classes": {"write_only": True}
        }

    # 属性级别校验 方法名格式validate_属性名
    # def validate_name(self,value):
    #     if "drf" not in value.lower():
    #         raise serializers.ValidationError("用户名需要包含drf")
    #     return value

    # 对象级别校验 重写validate方法
    def validate(self, attrs):
        if "drf" not in attrs.get("name").lower():
            raise serializers.ValidationError("用户名需要包含drf")

        if attrs.get("age")<18:
            raise serializers.ValidationError("用户年龄不能小于18岁")

        return attrs


# 简化版学生序列化器
class StudentSerializerSimple(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = ["id","name","age","sex"]

# 班级序列化器
class ClassSerializer(serializers.ModelSerializer):

    # 序列化器嵌套 在一个序列化器中嵌套另外一个序列化器
    # 属性名就是管理器名  many=True 学生有很多个，新增班级时不需要对学生信息修改，设置只读
    # 命名就必须是，tudent_set ， 关联表名_set

    # 属性名就是管理器名
    student_set = StudentSerializerSimple(many=True,read_only=True)
    class Meta:
        model = Classes
        exclude = ["is_delete"]